package cn.nkpro.elcube.components.pipeline.services;

import cn.nkpro.elcube.co.spel.NkAbstractHttpSpELInjection;
import cn.nkpro.elcube.docengine.service.NkPipelineService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 自己调用自己
 */
@Component("SpELpipeline")
public class NkSpELPipeline extends NkAbstractHttpSpELInjection {

    private Pattern pattern = Pattern.compile("(\\w+)(\\?(\\w+(=[^&=%?]*)?([&]\\w+(=[^&=%?]*)?)*))?");

    @Autowired
    private NkPipelineService pipelineService;

    public Object invoke(String url){
        Matcher matcher = pattern.matcher(url);
        if(matcher.matches()){
            String docType = matcher.group(1);
            String queryString = matcher.group(3);

            Map<String, String> collect = Arrays.stream(StringUtils.split(queryString, "&"))
                    .map(item -> StringUtils.split(item, "="))
                    .collect(Collectors.toMap(
                            e -> e[0],
                            e -> {
                                if(e.length>=2){
                                    try {
                                        return URLDecoder.decode(e[1],"UTF-8");
                                    } catch (UnsupportedEncodingException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                                return StringUtils.EMPTY;
                            }
                    ));
            return pipelineService.invoke(docType, collect);
        }
        return null;
    }
}
